package com.ctsi.organise.service;

import com.ctsi.commons.util.UtilValidate;
import com.ctsi.commons.util.id.UUIDGenerator;
import com.ctsi.framework.mybatis.support.MybatisEntityDao;
import com.ctsi.organise.entity.OrganiseEntity;
import com.ctsi.organise.entity.OrganiseStruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: zhangjw
 * @Date: 2018/11/15 20:33
 * @Description:
 */
@Repository
public class OrganiseStructManager extends MybatisEntityDao<OrganiseStruct> {

    @Autowired
    private OrganiseEntityManager organiseEntityManager;

    /**
     * 组织中加入组织时，维护闭包表
     * @param organ
     */
    public void organiseJoin(OrganiseEntity organ){
        List<OrganiseEntity> parents = new ArrayList<>();
        parents.add(organ);
        organiseEntityManager.getParentOrgans(organ.getParentId(), parents);
        for(OrganiseEntity org : parents){
            OrganiseStruct struct = new OrganiseStruct();
            struct.setId(UUIDGenerator.getId());
            struct.setAncestorId(org.getId());
            struct.setDescendantId(organ.getId());
            struct.setDistance(parents.indexOf(org));
            this.insert(struct);
        }
    }


    public void refreshStruct(){
        reBuildStruct(null);
    }

    /**
     * 重建闭包表
     */
    private void reBuildStruct(OrganiseEntity organiseEntity){
        if (organiseEntity == null) {
            organiseEntity = organiseEntityManager.findOrganiseEntityById(IOrganiseService.DEFAULT_ORGAN_ROOT);
            // 清空表
            this.delete(OrganiseStruct.class.getName()+".deleteAll");
            this.organiseJoin(organiseEntity);
            reBuildStruct(organiseEntity);
        } else {
            List<OrganiseEntity> result = organiseEntityManager.findByParentId(organiseEntity.getPartyId());
            if (UtilValidate.isNotEmpty(result)) {
                result.stream().forEach(organ -> {
                    this.organiseJoin(organ);
                    reBuildStruct(organ);
                });
            }
        }
    }

}
